package com.alingrad.android.froyoengine.graphics.renderable;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

import com.alingrad.android.froyoengine.graphics.Renderable;
import com.alingrad.android.froyoengine.util.GLColor;
import com.alingrad.android.froyoengine.util.GLHelper;

public abstract class Primitive extends Renderable {
	protected FloatBuffer mVertexBuffer;
	protected ShortBuffer mIndexBuffer;
	protected GLColor mColor;
	
	public Primitive() {
		super();
		mColor = GLColor.WHITE;
	}
	
	protected void createVertexBuffer(float[] vertices) {
		ByteBuffer bb = ByteBuffer.allocateDirect(vertices.length * 4);
		bb.order(ByteOrder.nativeOrder());
		mVertexBuffer = bb.asFloatBuffer();
		mVertexBuffer.put(vertices);
		mVertexBuffer.position(0);
	}
	
	protected void createIndexBuffer(short[] indices) {
		ByteBuffer bb = ByteBuffer.allocateDirect(indices.length * 2);
		bb.order(ByteOrder.nativeOrder());
		mIndexBuffer = bb.asShortBuffer();
		mIndexBuffer.put(indices);
		mIndexBuffer.position(0);
	}
	
	public void setColor(GLColor color) {
		mColor = color;
	}
	
	@Override
	public void draw(GL10 gl, float x, float y, float z, float scaleX, float scaleY, float rotation) {
		gl.glPushMatrix();
			GLHelper.setMatrix(gl, x, y, z, scaleX, scaleY, rotation);
			GLHelper.setColor(gl, mColor);
			gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
			gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
			gl.glDrawElements(GL10.GL_TRIANGLES, mIndexBuffer.capacity(), GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
		gl.glPopMatrix();
	}
}
